﻿using iMES.Core.BaseProvider;
using iMES.Core.Extensions;
using iMES.Core.Utilities;
using iMES.Custom.IRepositories;
using iMES.Entity.DomainModels;
using iMES.WorkManShip.IRepositories;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace iMES.WorkManShip.Services
{
    /// <summary>
    /// 班组
    /// </summary>
    public partial class WM_ExceptionService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IWM_ExceptionRepositoriec _repository;//访问数据库
        private readonly IBase_NumberRuleRepository _numberRuleRepository;
        public WM_ExceptionService(IHttpContextAccessor httpContextAccessor, IWM_ExceptionRepositoriec repository, IBase_NumberRuleRepository numberRuleRepository) : base(repository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = repository;
            _numberRuleRepository = numberRuleRepository;
        }
        WebResponseContent webResponse = new WebResponseContent();
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            AddOnExecuting = (Team_ShiftManagements defectItem, object list) =>
            {
                if (string.IsNullOrWhiteSpace(defectItem.TeamCode))
                    defectItem.TeamCode = GetDefectItemCode();
                //如果返回false,后面代码不会再执行、
                if (repository.Exists(x => x.TeamName == defectItem.TeamName))
                {
                    return webResponse.Error("工序管理名称已存在");
                }
                if (repository.Exists(x => x.TeamCode == defectItem.TeamCode))
                {
                    return webResponse.Error("工序管理编号已存在");
                }
                return webResponse.OK();
            };
            //扩展字段开始 start
            AddOnExecuted = (Team_ShiftManagements defectItem, object list) =>
            {
                return webResponse.OK();
            };
            //扩展字段开始 end
            return base.Add(saveDataModel);
        }
        
        /// <summary>
        /// 删除班组
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="delList"></param>
        /// <returns></returns>
        public override WebResponseContent Del(object[] keys, bool delList = false)
        {
            base.DelOnExecuted = (object[] defectItemIds) =>
            {
                return new WebResponseContent() { Status = true };
            };
            return base.Del(keys, delList);
        }
        public override WebResponseContent Update(SaveModel saveDataModel)
        {
            try
            {
                // 编辑前校验
                UpdateOnExecuting = (Team_ShiftManagements defectItem, object addList, object updateList, List<object> delKeys) =>
                {
                    if (repository.Exists(x => x.TeamName == defectItem.TeamName && x.Id != defectItem.Id))
                    {
                        return webResponse.Error("工序管理名称已存在");
                    }
                    if (repository.Exists(x => x.TeamCode == defectItem.TeamCode && x.Id != defectItem.Id))
                    {
                        return webResponse.Error("工序管理编号已存在");
                    }
                    // 其他业务校验可在此补充
                    return webResponse.OK();
                };

                // 编辑后处理
                base.UpdateOnExecuted = (Team_ShiftManagements defectItem, object obj1, object obj2, List<object> List) =>
                {
                    return new WebResponseContent(true);
                };

                return base.Update(saveDataModel);
            }
            catch (Exception ex)
            {
                // 捕获并返回详细异常信息
                var errorMsg = ex.InnerException?.Message ?? ex.Message;
                return webResponse.Error("更新失败：" + errorMsg);
            }
        }
        /// <summary>
        /// 自动生成班组编号
        /// </summary>
        /// <returns></returns>
        public string GetDefectItemCode()
        {
            DateTime dateNow = (DateTime)DateTime.Now.ToString("yyyy-MM-dd").GetDateTime();
            //查询当天最新的订单号
            string defectItemCode = repository.FindAsIQueryable(x => x.CreateDate > dateNow && x.TeamCode.Length > 8)
                .OrderByDescending(x => x.TeamCode)
                .Select(s => s.TeamCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "DefectItem")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    rule += (defectItemCode.Substring(defectItemCode.Length - numberRule.SerialNumber).GetInt() + 1).ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }
                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }
    }
}
